package com.immo.libcommon.http;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.immo.libcommon.base.BaseActivity;
import com.immo.libcommon.base.BaseBean;
import com.immo.libcommon.constant.RouterUtil;
import com.immo.libcommon.constant.SharePreferenceKey;
import com.immo.libcommon.utils.NetConnectUtils;
import com.immo.libcommon.utils.SharePreferenceUtils;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;

import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;

import static com.immo.libcommon.constant.ReturnCode.PAGE_NOT_FOUND;
import static com.immo.libcommon.constant.ReturnCode.SUCCESS_CODE;
import static com.immo.libcommon.utils.ToastUtils.showToast;

/**
 * @author Administrator
 * @content 网络连接类
 * @date 2017/11/10
 */
@SuppressWarnings("unused")
public class NetworkRequest {
    /**
     * 请求成功接口
     */
    private static RequestSuccess mRequestSuccess;
    /**
     * 请求失败接口
     */
    private static RequestFail mRequestFail;
    /**
     * 加载进度条
     */
    private KProgressHUD kProgressHUD;

    /**
     * 成功结果处理
     *
     * @param mRequestSuccess 成功结果的回调
     */
    public NetworkRequest(RequestSuccess mRequestSuccess) {
        NetworkRequest.mRequestSuccess = mRequestSuccess;
    }

    /**
     * 成功，失败结果的处理
     *
     * @param mRequestSuccess 成功结果回调
     * @param mRequestFail    失败结果回调
     */
    public NetworkRequest(RequestSuccess mRequestSuccess, RequestFail mRequestFail) {
        NetworkRequest.mRequestSuccess = mRequestSuccess;
        NetworkRequest.mRequestFail = mRequestFail;
    }

    public NetworkRequest() {
    }


    /**
     * 请求数据回调
     *
     * @param context    上下文
     * @param clazz      转换类
     * @param progress   是否显示进度条
     * @param isShowFail 是否要对错误返回进行特殊处理
     * @return 回调数据
     */
    private StringCallback stringCallBack(final Context context, final Class clazz, final boolean progress, final boolean isShowFail) {
        return new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                BaseBean baseBean = JSON.parseObject(response.body(), BaseBean.class);
                //请求成功
                if (baseBean.isSuccess() == SUCCESS_CODE || baseBean.getCode() == 0) {
                    mRequestSuccess.loadHttp(JSON.parseObject(response.body(), clazz), response.body());
                } else {
                    if (isShowFail) {
                        mRequestFail.loadHttpError(baseBean.getState());
                    } else {
                        if (baseBean.getMessage().equals("invalid token") || baseBean.getMessage().equals("jwt expired")) {
                            showToast(context, "登录信息已失效，请重新登录");
                            if (context instanceof BaseActivity) {
                                ((BaseActivity) context).finish();
                            }
                            ARouter.getInstance().build(RouterUtil.LOGIN_PAGE).withFlags(Intent.FLAG_ACTIVITY_NEW_TASK).navigation();
                        } else {
                            showToast(context, baseBean.getMessage());
                        }
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);

                if (response.code() == PAGE_NOT_FOUND) {
                    showToast(context, "页面不存在");
                } else {
                    try {
                        showToast(context, new JSONObject(Objects.requireNonNull(response.getRawResponse().body()).string()).getString("message"));
                    } catch (IOException | JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onFinish() {
                //网络请求结束，进度条结束
                if (context != null) {
                    if (context instanceof BaseActivity) {
                        if (!((BaseActivity) context).isFinishing()) {
                            kProgressHUD.dismiss();
                        }
                    }else {
                        kProgressHUD.dismiss();
                    }
                }
            }

            @Override
            public void onStart(com.lzy.okgo.request.base.Request<String, ? extends com.lzy
                    .okgo.request.base.Request> request) {
                super.onStart(request);
                kProgressHUD = new KProgressHUD(context);
                //如果进度条开启的情况下，在网络请求开始的情况下启动进度条
                if (progress) {
                    kProgressHUD.show();
                }
            }
        };
    }

    /**
     * 获取Token
     *
     * @param context 上下文
     * @return Token
     */
    private String getToken(Context context) {
        return "Bearer " + Objects.requireNonNull(SharePreferenceUtils.get(context, SharePreferenceKey.TOKEN, "")).toString();
    }


    /**
     * 普通的Get请求
     *
     * @param url        请求地址
     * @param context    上下文
     * @param clazz      基类
     * @param progress   进度条
     * @param isShowFail 是否要对错误返回进行特殊处理
     */

    public void requestGet(final String url, final Context context, final Class clazz, final boolean progress, boolean isShowFail) {
        if (new NetConnectUtils().isNetworkConnected(context)) {
            showToast(context, "网络连接异常，请检查后重试");
            return;
        }
        OkGo.<String>get(url)
                .headers("Authorization", getToken(context))
                .execute(stringCallBack(context, clazz, progress, isShowFail));
    }

    /**
     * 普通的Post键值对请求
     *
     * @param url        请求地址
     * @param context    上下文
     * @param json       请求参数
     * @param clazz      基类
     * @param progress   进度条
     * @param isShowFail 是否要对错误返回进行特殊处理
     */
    public void requestPostKey(final String url, final Context context, final HashMap<String, String> json, final Class clazz, final boolean progress, boolean isShowFail) {
        if (new NetConnectUtils().isNetworkConnected(context)) {
            showToast(context, "网络连接异常，请检查后重试");
            return;
        }
        OkGo.<String>post(url)
                .params(json)
                .headers("Authorization", getToken(context))
                .execute(stringCallBack(context, clazz, progress, isShowFail));

    }

    /**
     * 普通的Post请求
     *
     * @param url        请求地址
     * @param context    上下文
     * @param json       请求参数
     * @param clazz      基类
     * @param progress   进度条
     * @param isShowFail 是否要对错误返回进行特殊处理
     */
    public void requestPost(final String url, final Context context, final String json, final Class clazz, final boolean progress, boolean isShowFail) {
        if (new NetConnectUtils().isNetworkConnected(context)) {
            showToast(context, "网络连接异常，请检查后重试");
            return;
        }
        OkGo.<String>post(url)
                .upJson(json != null ? json : "")
                .headers("Authorization", getToken(context))
                .execute(stringCallBack(context, clazz, progress, isShowFail));
    }
}
